/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package madmac.hibernate.util;

import madmac.exception.DataAccessLayerException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author atila
 */
public class HibernateUtil {

	private static SessionFactory sessionFactory;
	 private static HibernateUtil instance;

	 private HibernateUtil(){}

	 public static HibernateUtil getInstance() {
		 if (instance == null) {
			 instance = new HibernateUtil();
		 }
		 return instance;
	 }

    public static SessionFactory buildSessionFactory() throws HibernateException {
		 if (sessionFactory != null) {
			 closeFactory();
		 }
		 return configureSessionFactory();
	 }

	 public static SessionFactory configureSessionFactory() throws HibernateException {
		Configuration configuration = new Configuration();
		configuration.configure();
		sessionFactory = configuration.buildSessionFactory();
		return sessionFactory;
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

	 public static Session openSession () throws HibernateException, DataAccessLayerException {
		 instance.buildIfNeeded();
		 return sessionFactory.openSession();
	 }

	 public SessionFactory buildIfNeeded() throws DataAccessLayerException {
		 if (sessionFactory != null) {
			 return sessionFactory;
		 }
		 try {
			 return configureSessionFactory();
		 } catch (HibernateException e) {
			 throw new DataAccessLayerException(e);
		 }
	 }

	 public static void closeFactory() {
		 if (sessionFactory != null) {
			 sessionFactory.close();
		 }
	 }

	 public static void close(Session session) {
		 if (session != null) {
			 session.close();
		 }
	 }

	 public static void rollback(Transaction tx) {
		 if (tx != null) {
			 tx.rollback();
		 }
	 }
}